class SocketClient {
	url = "";
	onReFn = null;
	onSucFn = null;
	onErrFn = null;

	isSocketClose = false;
	reconnectCount = 1;
	heartbeatInterval = "";
	socketTask = null;

	againTimer = null;

	area_id = null;
	constructor(socketUrl, onReceive, onErrorEvent, onErrorSucceed, area_id = null) {
		//WebSocket的地址
		// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
		this.url = socketUrl
		// console.log("socket url",this.url)
		// 连接
		this.onReFn = onReceive;
		this.onErrFn = onErrorEvent;
		this.onSucFn = onErrorSucceed;
		this.isSocketClose = false;
		this.area_id = "" + area_id;
		//判断是否有websocet对象，有的话清空
		if (this.socketTask) {
			this.socketTask.close();
			if (this.heartbeatInterval) {
				clearInterval(this.heartbeatInterval);
			}
		}
		this.socketTask = uni.connectSocket({
			url: this.url,
			//必须是箭头函数，否则拿不到this
			success: (data) => {
				if (this.againTimer) {
					clearInterval(this.againTimer)
				}
				this.isConnected = true
			},
			fail: (err) => {
				console.log("报错", err);
			}
		});

		// 连接打开
		this.socketTask.onOpen((res) => {
			console.log("onOpen===",res)
			// console.log('WebSocket打开');
			clearInterval(this.againTimer) //断线重连定时器
			onErrorSucceed({
				isShow: false
			}) // 用于提示框的隐藏
			this.heartbeatInterval && clearInterval(this.heartbeatInterval);
			// 5秒发送一次心跳
			// console.log("1============心跳")
			this.heartbeatInterval = setInterval(() => {
				this.sendMsg('PING')
			}, 1000 * 5)
		})
		// 监听连接失败
		this.socketTask.onError((err) => {
			// console.log('WebSocket连接打开失败，请检查', err);
			//停止发送心跳
			clearInterval(this.heartbeatInterval)
			//如果不是人为关闭的话，进行重连
			if (!this.isSocketClose) {
				this.reconnect(this.url, this.onErrFn)
			}
		})

		// 监听连接关闭 -
		this.socketTask.onClose((e) => {
			console.error("断开连接",e)
			// console.log('WebSocket连接关闭！');
			clearInterval(this.heartbeatInterval)
			if (!this.isSocketClose) {
				this.reconnect(this.url, this.onErrFn)
			}
		})

		// 监听收到信息
		this.socketTask.onMessage((res) => {
			// 如果是心跳,直接回复
			if(res.data=="PING"){
				console.error("PONG")
				this.socketTask.send("PONG")
			}
			let serverData = res.data
			//与后端规定好返回值分别代表什么，写业务逻辑
			serverData && this.onReFn(serverData);
		});

		return this
	}

	reconnect = (url, onErrorEvent) => {
		// console.log('进入断线重连', this.isSocketClose);
		clearInterval(this.againTimer) //断线重连定时器
		clearInterval(this.heartbeatInterval);
		this.socketTask && this.socketTask.close(); // 确保已经关闭后再重新打开
		this.socketTask = null;
		onErrorEvent({
			isShow: true,
			message: '重连中，请稍后...'
		})
		// 连接  重新调用创建websocet方法
		if (this.reconnectCount <= 0) {
			return uni.showToast({
				icon: "none",
				title: "已超出重连次数",
				duration: 3000
			})
		}
		this.againTimer = setInterval(() => {
			let skt = new SocketClient(this.url, this.onReFn, this.onErrFn, this.onSucFn, this.area_id)
			this.reconnectCount--
			skt.reconnectCount = this.reconnectCount
			// 停止当前的客户端计时器
			console.log('在重新连接中...');
			clearInterval(this.againTimer)
		}, 1000 * 5)
	}

	sendMsg = (msg) => { //向后端发送命令
		msg = JSON.stringify(msg)
		try {
			//通过 WebSocket 连接发送数据
			this.socketTask.send({
				data: msg
			});
		} catch (e) {
			if (this.isSocketClose) {
				return
			} else {
				this.reconnect(this.url, this.onErrFn)
			}
		}
	}



	stop = () => {
		this.isSocketClose = true
		clearInterval(this.heartbeatInterval);
		clearInterval(this.againTimer) //断线重连定时器
		if(this.socketTask){
			this.socketTask.close(); // 确保已经关闭后再重新打开
		}
		this.socketTask = null;
	}

}


export default SocketClient